﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace LitTools
{
    /// <summary>
    /// 点击过滤器UI
    /// </summary>
    public class PointerFilterMono : MonoWithFilterQueue, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler
    {
        //缓存按下的物体
        private readonly List<GameObject> pointerDownGos = new();
        //射线穿透结果
        private readonly List<RaycastResult> raycastResult = new();

        public event Action PointerClickAct;
        public event Action PointerDownAct;
        public event Action PointerUpAct;

        public void OnPointerClick(PointerEventData eventData)
        {
            PointerClickAct?.Invoke();
            EventSystem.current.RaycastAll(eventData, raycastResult);
            raycastResult.RemoveAt(0);
            var targets = PassFilterQueue(raycastResult);
            if (targets == null) return;
            for (int i = 0; i < targets.Count; i++)
            {
                ExecuteEvents.Execute(targets[i].gameObject, eventData, ExecuteEvents.pointerClickHandler);
            }
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            PointerDownAct?.Invoke();
            EventSystem.current.RaycastAll(eventData, raycastResult);
            raycastResult.RemoveAt(0);
            var targets = PassFilterQueue(raycastResult);
            if (targets == null) return;
            for (int i = 0; i < targets.Count; i++)
            {
                pointerDownGos.Add(targets[i].gameObject);
                ExecuteEvents.Execute(targets[i].gameObject, eventData, ExecuteEvents.pointerDownHandler);
            }
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            PointerUpAct?.Invoke();
            for (int i = 0; i < pointerDownGos.Count; i++)
            {
                ExecuteEvents.Execute(pointerDownGos[i], eventData, ExecuteEvents.pointerUpHandler);
            }
            pointerDownGos.Clear();
        }
    }
}